import {
  getMailVer,
  login,
  mailVer,
  register,
  logingetMailVer,
  loginMailVer,
  getQRcode,
  isLogin,
  updateAvatar,
  getAvatar,
  updateNickName,
  updateGender,
  updatePassword,
} from "./api.js";

$(function () {
  // 进入页面先查看登录状态
  if (localStorage.getItem("token") && localStorage.getItem("userHeadUrl")) {
    $(".login-form").css({
      display: "none",
    });
    $(".code-form").css({
      display: "none",
    });
    $(".create-form").css({
      display: "none",
    });
    $(".weixin").css({
      display: "none",
    });
    $(".login-success").css({
      display: "block",
    });
    $(".bg-text2").css({
      display: "none",
    });

    // 渲染个人信息
    $("#userHead").attr("src", localStorage.getItem("userHeadUrl"));
    $("#name").text("昵称：" + localStorage.getItem("nickName"));
    if (
      localStorage.getItem("gender") === "男" ||
      localStorage.getItem("gender") === "女"
    ) {
      $("#sex").text("性别：" + localStorage.getItem("gender"));
    } else {
      $(".setSex").css({ display: "inline-block" });
    }
  }

  // --------------登录注册切换--------------
  //#region
  $(".to-create").click(function () {
    $(".login-form").css({
      display: "none",
    });
    $(".code-form").css({
      display: "none",
    });
    $(".create-form").css({
      display: "block",
    });
  });
  $(".to-login").click(function () {
    $(".login-form").css({
      display: "block",
    });
    $(".code-form").css({
      display: "bobe",
    });
    $(".create-form").css({
      display: "none",
    });
    $(".userInfo-form").css({
      display: "none",
    });
  });
  $(".userInfo-to-login").click(function () {
    $(".login-form").css({
      display: "block",
    });
    $(".code-form").css({
      display: "none",
    });
    $(".create-form").css({
      display: "none",
    });
    $(".userInfo-form").css({
      display: "none",
    });
  });
  $(".to-code").click(function () {
    $(".login-form").css({
      display: "none",
    });
    $(".code-form").css({
      display: "block",
    });
    $(".create-form").css({
      display: "none",
    });
    $(".userInfo-form").css({
      display: "none",
    });
  });
  $(".to-mail").click(function () {
    $(".login-form").css({
      display: "block",
    });
    $(".code-form").css({
      display: "none",
    });
    $(".create-form").css({
      display: "none",
    });
    $(".userInfo-form").css({
      display: "none",
    });
  });
  //#endregion

  // -------------------注册-------------------
  var email = "";
  var vercode = "";
  var createAgree = false;
  // 1.点击获取验证码
  $(".get-vercode").click(function () {
    email = $(".input-email").val();
    createAgree = $(".checkbox-agree-create").prop("checked");
    if (email === "") {
      layer.msg("请输入邮箱");
      return;
    } else if (createAgree === false) {
      layer.msg("请勾选同意《用户协议》和《隐私协议》");
      return;
    }
    // 验证码倒计时
    var s = 60; //预定义总秒数
    $(this).text("重新获取(60s)"); //单击之后立刻更改按钮val，减少延迟
    $(this).attr("disabled", "true").css("cursor", "not-allowed"); //增加不可操作属性
    var timer = setInterval(function () {
      s--; //衔接之前更改的秒数
      $(".get-vercode").text("重新获取(" + s + "s)");
      //如果秒数为0，关闭定时器
      if (s == 0) {
        //修改按钮val
        $(".get-vercode").text("获取验证码");
        //去除不可操作属性
        $(".get-vercode").removeAttr("disabled").css("cursor", "pointer");
        s = 60; //因为秒数已经结束了，这里要重新开始，方便下次单击重新获取验证码
        clearInterval(timer);
      }
    }, 1000);
    getMailVer({
      email,
    }).catch(() => {
      layer.msg("获取验证码失败", { icon: 0 });
    });
  });
  // 2.注册
  $(".button-create").click(function () {
    email = $(".input-email").val();
    vercode = $(".input-vercode").val();
    createAgree = $(".checkbox-agree-create").prop("checked");
    // 表单预校验
    if (email === "") {
      layer.msg("请输入邮箱");
      return;
    } else if (vercode === "") {
      layer.msg("请输入验证码");
      return;
    } else if (createAgree === false) {
      layer.msg("请勾选同意《用户协议》和《隐私协议》");
      return;
    }
    // 2-1.检验邮箱验证码
    mailVer({
      email: email,
      code: vercode,
    })
      .then((result) => {
        if (result.data.message === "验证码不匹配") {
          layer.msg("邮箱或验证码错误", { icon: 0 });
          return;
        } else {
          layer.msg("验证码校验成功", { icon: 1 });
          $(".login-form").css({
            display: "none",
          });
          $(".create-form").css({
            display: "none",
          });
          $(".weixin").css({
            display: "none",
          });
          $(".userInfo-form").css({
            display: "block",
          });
          $(".input-setmail").val(email);
          $(".button-userInfo").click(function () {
            if ($(".input-setname").val() === "") {
              layer.msg("请输入姓名");
              return;
            } else if ($(".select-setgender").val() === "") {
              layer.msg("请选择性别");
              return;
            } else if ($(".input-setpsd").val() === "") {
              layer.msg("请输入密码");
              return;
            } else {
              // 2-2.完成用户注册
              register({
                nickName: $(".input-setname").val(),
                gender: $(".input-setgender").val(),
                email,
                password: $(".input-setpsd").val(),
              })
                .then((result) => {
                  if (result.data.message === "注册失败！") {
                    layer.msg("注册失败！邮箱已被注册！", { icon: 0 });
                  } else {
                    layer.msg("注册成功", { icon: 1 });
                    $(".login-form").css({
                      display: "block",
                    });
                    $(".create-form").css({
                      display: "none",
                    });
                    $(".weixin").css({
                      display: "block",
                    });
                    $(".userInfo-form").css({
                      display: "none",
                    });
                  }
                })
                .catch(() => {});
            }
          });
        }
      })
      .catch((error) => {
        layer.msg("邮箱或验证码错误", { icon: 0 });
        console.log(error);
      });
  });

  // -------------------登录-------------------
  var username = "";
  var password = "";
  var agree = false;
  // 点击登录拿到输入框的值
  $(".button-submit").click(function () {
    username = $(".input-username").val();
    password = $(".input-password").val();
    agree = $(".checkbox-agree").prop("checked");
    if (username === "") {
      layer.msg("请输入账号");
      return;
    } else if (password === "") {
      layer.msg("请输入密码");
      return;
    } else if (agree === false) {
      layer.msg("请勾选同意《用户协议》和《隐私协议》");
      return;
    }
    // 请求后端-登录
    login({
      email: username,
      password: password,
    })
      .then((result) => {
        if (result.data.message == "登录成功！") {
          layer.msg("登录成功", { icon: 1 });
          // 隐藏登录表单显示登录成功页面
          $(".login-success").css({
            display: "block",
          });
          $(".login-form").css({
            display: "none",
          });
          $(".weixin").css({
            display: "none",
          });
          $(".bg-text2").css({
            display: "none",
          });
          // 保存token、头像、性别、昵称
          localStorage.setItem("token", result.data.data.token);
          localStorage.setItem("userHeadUrl", result.data.data.avatarUrl);
          localStorage.setItem("gender", result.data.data.gender);
          localStorage.setItem("nickName", result.data.data.nickName);

          // 渲染页面
          $("#userHead").attr("src", localStorage.getItem("userHeadUrl"));
          $("#name").text("昵称：" + localStorage.getItem("nickName"));
          if (
            localStorage.getItem("gender") === "男" ||
            localStorage.getItem("gender") === "女"
          ) {
            $("#sex").text("性别：" + localStorage.getItem("gender"));
          } else {
            $(".setSex").css({ display: "inline-block" });
          }

          // 刷新
          location.reload();
        } else {
          layer.msg("邮箱或密码错误", { icon: 0 });
          return;
        }
      })
      .catch(() => {
        layer.msg("邮箱或密码错误", { icon: 0 });
      });
  });

  // ------------------验证码登录------------------
  // 1.点击获取验证码
  $(".get-logcode").click(function () {
    email = $(".input-logcode").val();
    createAgree = $(".checkbox-agree-code").prop("checked");
    // 表单预校验
    if (email === "") {
      layer.msg("请输入邮箱");
      return;
    } else if (createAgree === false) {
      layer.msg("请勾选同意《用户协议》和《隐私协议》");
      return;
    }
    // 验证码倒计时
    var s = 60; //预定义总秒数
    $(this).text("重新获取(60s)"); //单击之后立刻更改按钮val，减少延迟
    $(this).attr("disabled", "true").css("cursor", "not-allowed"); //增加不可操作属性
    var timer = setInterval(function () {
      //定时器
      s--; //衔接之前更改的秒数
      $(".get-logcode").text("重新获取(" + s + "s)");
      //如果秒数为0，关闭定时器
      if (s == 0) {
        //修改按钮val
        $(".get-logcode").text("获取验证码");
        //去除不可操作属性
        $(".get-logcode").removeAttr("disabled").css("cursor", "pointer");
        s = 60; //因为秒数已经结束了，这里要重新开始，方便下次单击重新获取验证码
        clearInterval(timer);
      }
    }, 1000);
    logingetMailVer({
      email,
    }).catch((error) => {
      layer.msg("获取验证码失败", { icon: 0 });
      console.log(error);
    });
  });
  // 2.登录
  $(".button-logcode").click(function () {
    email = $(".input-logcode").val();
    vercode = $(".input-code").val();
    createAgree = $(".checkbox-agree-code").prop("checked");
    // 表单预校验
    if (email === "") {
      layer.msg("请输入邮箱");
      return;
    } else if (vercode === "") {
      layer.msg("请输入验证码");
      return;
    } else if (createAgree === false) {
      layer.msg("请勾选同意《用户协议》和《隐私协议》");
      return;
    }
    // 2.邮箱验证码登录
    loginMailVer({
      email: email,
      code: vercode,
    })
      .then((res) => {
        if (res.data.message != "登录成功！") {
          layer.msg("邮箱或验证码错误", { icon: 0 });
          return;
        } else {
          layer.msg("登录成功", { icon: 1 });
          $(".code-form").css({
            display: "none",
          });
          $(".login-success").css({
            display: "block",
          });
          $(".weixin").css({
            display: "none",
          });
          $(".bg-text2").css({
            display: "none",
          });
          localStorage.setItem("token", res.data.data.token);
          localStorage.setItem("userHeadUrl", res.data.data.avatarUrl);
          localStorage.setItem("gender", res.data.data.gender);
          localStorage.setItem("nickName", res.data.data.nickName);

          // 渲染页面
          $("#userHead").attr("src", localStorage.getItem("userHeadUrl"));
          $("#name").text("昵称：" + localStorage.getItem("nickName"));
          if (
            localStorage.getItem("gender") === "男" ||
            localStorage.getItem("gender") === "女"
          ) {
            $("#sex").text("性别：" + localStorage.getItem("gender"));
          } else {
            $(".setSex").css({ display: "inline-block" });
          }
          // 刷新
          location.reload();
        }
      })
      .catch((error) => {
        layer.msg("邮箱或验证码错误", { icon: 0 });
        console.log(error);
      });
  });

  // -------------------微信登录-------------------
  $(".weixin").click(function () {
    if ($(".checkbox-agree").prop("checked") === false) {
      layer.msg("请勾选同意《用户协议》和《隐私协议》");
      return;
    }
    // 2s内禁用
    var s = 2;
    $(".weixin").attr("disabled", "true").css("cursor", "not-allowed"); //不可操作
    var t = setInterval(function () {
      //定时器
      s--; //如果秒数为0，关闭定时器
      if (s == 0) {
        $(".weixin").removeAttr("disabled").css("cursor", "pointer");
        s = 2; //重新开始
        clearInterval(t);
      }
    }, 1000);
    getQRcode()
      .then((result) => {
        var layerWx = layer.open({
          type: 1,
          area: ["30vw", "30vw"], // 宽高
          title: false, // 不显示标题栏
          closeBtn: 0,
          shadeClose: true, // 点击遮罩关闭层
          content:
            '<div class="wx-box"><img src="' +
            result.data.data.qrUrl +
            '"></div>',
          end: function () {
            layer.msg("取消微信登录", { icon: 0 });
            clearInterval(timer);
          },
        });
        // 轮询判断用户是否已经登录
        var timer = null;
        timer = setInterval(() => {
          isLogin({ tempUserId: result.data.data.tempUserId })
            .then((res) => {
              if (res.data.message === "登录成功！") {
                layer.close(layerWx);
                layer.msg("登录成功", { icon: 1 });
                // 隐藏登录表单显示登录成功页面
                $(".login-success").css({
                  display: "block",
                });
                $(".login-form").css({
                  display: "none",
                });
                $(".weixin").css({
                  display: "none",
                });
                $(".bg-text2").css({
                  display: "none",
                });
                localStorage.setItem("token", res.data.data.token);
                localStorage.setItem("userHeadUrl", res.data.data.avatarUrl);
                localStorage.setItem("gender", res.data.data.gender);
                localStorage.setItem("nickName", res.data.data.nickName);

                // 渲染页面
                $("#userHead").attr("src", localStorage.getItem("userHeadUrl"));
                $("#name").text("昵称：" + localStorage.getItem("nickName"));
                if (
                  localStorage.getItem("gender") === "男" ||
                  localStorage.getItem("gender") === "女"
                ) {
                  $("#sex").text("性别：" + localStorage.getItem("gender"));
                } else {
                  $(".setSex").css({ display: "inline-block" });
                }
                clearInterval(timer);
                // 刷新
                location.reload();
              }
            })
            .catch(() => {
              clearInterval(timer);
              layer.msg("取消登录", { icon: 0 });
            });
        }, 1000);
      })
      .catch((error) => {
        console.log(error);
        layer.msg("二维码获取失败", { icon: 0 });
      });
  });

  // -------------------退出登录-------------------
  $(".logout").click(function () {
    $(".login-form").css({
      display: "block",
    });
    $(".weixin").css({
      display: "block",
    });
    $(".login-success").css({
      display: "none",
    });
    $(".bg-text2").css({
      display: "block",
    });
    localStorage.removeItem("token");
    localStorage.removeItem("userHeadUrl");
    localStorage.removeItem("nickName");
    localStorage.removeItem("gender");
  });
  // -------------------更换头像-------------------
  $(".sethead").click(function () {
    $(".select").change(function () {
      if ($(this).val() == "") {
        layer.msg("取消修改");
        return;
      }
      let file = $(this)[0].files[0];
      updateAvatar({ file })
        .then(() => {
          getAvatar()
            .then((result) => {
              localStorage.setItem("userHeadUrl", result.data);
              location.reload(); // 刷新
              layer.msg("头像更换成功", { icon: 1 });
            })
            .catch(() => {});
        })
        .catch(() => {
          layer.msg("头像上传失败", { icon: 0 });
        });
    });
  });
  // -------------------修改昵称-------------------
  $(".setName").click(function () {
    $("#name").text("昵称：");
    $(".setName").css({ display: "none" });
    $(".set").css({ display: "inline-block" });
  });
  $(".no").click(function () {
    $("#name").text("昵称：" + localStorage.getItem("nickName"));
    $(".setName").css({ display: "inline-block" });
    $(".set").css({ display: "none" });
  });
  $(".yes").click(function () {
    var newName = $(".input-setNewName").val();
    if (!newName.trim()) {
      layer.msg("昵称不能为空");
      return;
    }
    $(".setName").css({ display: "inline-block" });
    $(".set").css({ display: "none" });
    // 发请求-存本地-回显-通知
    updateNickName({ nickName: newName })
      .then(() => {
        localStorage.setItem("nickName", newName);
        $("#name").text("昵称：" + localStorage.getItem("nickName"));
        layer.msg("修改成功", { icon: 1 });
      })
      .catch(() => {
        layer.msg("修改失败", { icon: 0 });
      });
  });
  // -------------------修改性别-------------------
  layui.use(function () {
    var form = layui.form;
    var layer = layui.layer;
    // select 事件
    form.on("select(demo-select-filter)", function (data) {
      if (data.value != "") {
        var newSex = data.value;
        // 发请求-存本地-回显-通知
        updateGender({ gender: newSex })
          .then(() => {
            $("#sex").text("性别：" + newSex);
            $(".setSex").css({ display: "none" });
            localStorage.setItem("gender", newSex);
            layer.msg("修改成功", { icon: 1 });
          })
          .catch(() => {});
      } else {
        return;
      }
    });
  });
  // -------------------修改密码-------------------
  $(".setPsd").click(function () {
    $(".setPsd").css({ display: "none" });
    $(".setNewPsd").css({ display: "block" });
  });
  $("#setPsd").click(function () {
    if (!$(".input-newPsd").val().trim()) {
      layer.msg("密码不能为空");
      return;
    }
    // 删除
    $(".setPsd").css({ display: "block" });
    $(".setNewPsd").css({ display: "none" });
    updatePassword({
      oldPassword: $(".input-oldPsd").val(),
      newPassword: $(".input-newPsd").val(),
    })
      .then((result) => {
        if (result.data.message === "重设密码成功") {
          $(".setPsd").css({ display: "block" });
          $(".setNewPsd").css({ display: "none" });
          layer.msg("修改成功", { icon: 1 });
        } else {
          layer.msg("修改失败，旧密码不匹配", { icon: 0 });
        }
      })
      .catch(() => {
        layer.msg("修改失败，旧密码不匹配", { icon: 0 });
      });
  });
});
